// 检测设备类型
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768;

// 性能优化：根据设备性能调整动画
const isLowPerformance = isMobile && (navigator.hardwareConcurrency <= 2 || navigator.deviceMemory <= 2);


// 爱心点击特效
function createHeartEffect(x, y) {
    const heart = document.createElement('div');
    heart.innerHTML = ['❤️', '💖', '💕', '💗', '💓'][Math.floor(Math.random() * 5)];
    heart.style.position = 'fixed';
    heart.style.left = (x - 15) + 'px';
    heart.style.top = (y - 15) + 'px';
    heart.style.fontSize = '30px';
    heart.style.pointerEvents = 'none';
    heart.style.zIndex = '9999';
    heart.style.animation = 'heartFloat 1s ease-out forwards';
    
    document.body.appendChild(heart);
    
    setTimeout(() => {
        heart.remove();
    }, 1000);
}

// 页面滚动动画
function initScrollAnimations() {
    const sections = document.querySelectorAll('section');
    sections.forEach(section => {
        section.style.opacity = '0';
        section.style.transform = 'translateY(50px)';
        section.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    });
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, { threshold: 0.1 });
    
    sections.forEach(section => observer.observe(section));
}

document.addEventListener('DOMContentLoaded', function() {
    const loadingScreen = document.getElementById('loading-screen');
    
    // 初始化新功能
    initScrollAnimations();
    
    // 显示"我爱你"通知
    if ('Notification' in window) {
        if (Notification.permission === 'granted') {
            showLoveNotification();
        } else if (Notification.permission !== 'denied') {
            Notification.requestPermission().then(permission => {
                if (permission === 'granted') {
                    showLoveNotification();
                }
            });
        }
    }
    
    // 添加点击爱心特效
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.btn') && !e.target.closest('.modal')) {
            createHeartEffect(e.clientX, e.clientY);
        }
    });
    
    // 移动端触摸爱心特效
    if (isMobile) {
        document.addEventListener('touchstart', function(e) {
            const touch = e.touches[0];
            if (!touch.target.closest('.btn') && !touch.target.closest('.modal')) {
                createHeartEffect(touch.clientX, touch.clientY);
            }
        }, { passive: true });
    }
    
    // 移动端优化：预加载关键资源
    if (isMobile) {
        // 添加触摸优化
        document.body.style.webkitTouchCallout = 'none';
        document.body.style.webkitUserSelect = 'none';
        document.body.style.userSelect = 'none';
        
        // 防止双击缩放
        let lastTouchEnd = 0;
        document.addEventListener('touchend', function (event) {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);
    }
    
    const backgroundImage = new Image();
    backgroundImage.onload = function() {
        document.body.classList.add('bg-loaded');
        
        setTimeout(() => {
            loadingScreen.classList.add('hidden');
            
            setTimeout(() => {
                loadingScreen.style.display = 'none';
                // 移动端优化：加载完成后初始化交互
                if (isMobile) {
                    initMobileOptimizations();
                }
            }, 500);
        }, isMobile ? 600 : 800); // 移动端加载时间稍短
    };
    
    backgroundImage.onerror = function() {
        console.log('背景图片加载失败，使用默认背景');
        setTimeout(() => {
            loadingScreen.classList.add('hidden');
            setTimeout(() => {
                loadingScreen.style.display = 'none';
                if (isMobile) {
                    initMobileOptimizations();
                }
            }, 500);
        }, 1000);
    };
    
    backgroundImage.src = 'A.PNG';
    
    const timelineItems = document.querySelectorAll('.timeline-item');
    timelineItems.forEach((item, index) => {
        // 移动端优化：减少动画延迟
        const delay = isMobile ? index * 0.2 : index * 0.3;
        item.style.animationDelay = `${delay}s`;
    });
    
    // 移动端优化：调整 Intersection Observer 参数
    const observerOptions = {
        threshold: isMobile ? 0.05 : 0.1,
        rootMargin: isMobile ? '0px 0px -30px 0px' : '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, observerOptions);
    
    const animatedElements = document.querySelectorAll('.timeline-item, .confession, .buttons');
    animatedElements.forEach(el => {
        el.style.opacity = '0';
        el.style.transform = isMobile ? 'translateY(20px)' : 'translateY(30px)';
        el.style.transition = isMobile ? 'opacity 0.4s ease, transform 0.4s ease' : 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(el);
    });
});

// 移动端专用优化函数
function initMobileOptimizations() {
    // 优化按钮触摸反馈
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(btn => {
        btn.addEventListener('touchstart', function() {
            this.style.transform = 'scale(0.95)';
        }, { passive: true });
        
        btn.addEventListener('touchend', function() {
            setTimeout(() => {
                this.style.transform = '';
            }, 150);
        }, { passive: true });
    });
    
    // 优化模态框在移动端的显示
    const modal = document.getElementById('response-modal');
    if (modal) {
        modal.addEventListener('touchmove', function(e) {
            e.preventDefault();
        }, { passive: false });
    }
    
    // 移动端键盘适配
    if (window.visualViewport) {
        window.visualViewport.addEventListener('resize', function() {
            const modal = document.getElementById('response-modal');
            if (modal && modal.style.display === 'block') {
                const modalContent = modal.querySelector('.modal-content');
                if (modalContent) {
                    modalContent.style.marginTop = Math.max(10, (window.visualViewport.height - modalContent.offsetHeight) / 2) + 'px';
                }
            }
        });
    }
}

function showResponse(type) {
    const modal = document.getElementById('response-modal');
    const responseText = document.getElementById('response-text');
    
    // 移动端优化：调整字体大小和间距
    const fontSize = isMobile ? '1rem' : '1.2rem';
    const titleSize = isMobile ? '1.5rem' : '2rem';
    const marginBottom = isMobile ? '15px' : '20px';
    
    if (type === 'yes') {
        responseText.innerHTML = `
            <h2 style="color: #ff6b9d; margin-bottom: ${marginBottom}; font-size: ${titleSize};">💕 太好了！💕</h2>
            <p style="font-size: ${fontSize}; line-height: 1.6; padding: 0 ${isMobile ? '10px' : '0'};">
                你的答案让我的心都要飞起来了！<br>
                从今以后，让我们一起创造更多美好的回忆吧！<br>
                我会用我的全部去爱你，保护你，陪伴你。<br><br>
                <strong style="color: #ff6b9d;">我爱你！ ❤️</strong>
            </p>
            <div style="text-align: center; margin-top: 20px;">
                <img src="B.PNG" style="max-width: 100%; max-height: 200px; border-radius: 10px;">
            </div>
        `;
        // 移动端优化：减少庆祝动画数量以提升性能
        createCelebration();
    } else {
        responseText.innerHTML = `
            <h2 style="color: #4ecdc4; margin-bottom: ${marginBottom}; font-size: ${titleSize};">💭 没关系</h2>
            <p style="font-size: ${fontSize}; line-height: 1.6; padding: 0 ${isMobile ? '10px' : '0'};">
                我理解你需要时间思考。<br>
                无论你的决定是什么，我都会尊重。<br>
                我们的友谊永远不会改变，<br>
                你永远是我最珍贵的人。<br><br>
                <strong style="color: #4ecdc4;">慢慢想，不着急 😊</strong>
            </p>
            <div style="text-align: center; margin-top: 20px;">
                <img src="B.PNG" style="max-width: 100%; max-height: 200px; border-radius: 10px;">
            </div>
        `;
    }
    
    modal.style.display = 'block';
    
    // 移动端优化：防止背景滚动
    if (isMobile) {
        document.body.style.overflow = 'hidden';
        
        // 移动端模态框居中优化
        const modalContent = modal.querySelector('.modal-content');
        if (modalContent) {
            // 确保模态框在视口中央
            setTimeout(() => {
                const viewportHeight = window.innerHeight;
                const modalHeight = modalContent.offsetHeight;
                const topPosition = Math.max(20, (viewportHeight - modalHeight) / 2);
                modalContent.style.marginTop = topPosition + 'px';
                modalContent.style.marginBottom = '20px';
            }, 50);
        }
    }
    
    // 添加触摸关闭功能（移动端友好）
    if (isMobile) {
        let startY = 0;
        let currentY = 0;
        const modalContent = modal.querySelector('.modal-content');
        
        modalContent.addEventListener('touchstart', function(e) {
            startY = e.touches[0].clientY;
        }, { passive: true });
        
        modalContent.addEventListener('touchmove', function(e) {
            currentY = e.touches[0].clientY;
            const diff = currentY - startY;
            
            // 向下滑动超过50px时添加视觉反馈
            if (diff > 50) {
                this.style.transform = `translateY(${Math.min(diff - 50, 20)}px)`;
                this.style.opacity = Math.max(0.7, 1 - (diff - 50) / 200);
            }
        }, { passive: true });
        
        modalContent.addEventListener('touchend', function(e) {
            const diff = currentY - startY;
            
            // 向下滑动超过100px时关闭模态框
            if (diff > 100) {
                closeModal();
            } else {
                // 恢复原位
                this.style.transform = '';
                this.style.opacity = '';
            }
        }, { passive: true });
    }
}

function closeModal() {
    const modal = document.getElementById('response-modal');
    const modalContent = modal.querySelector('.modal-content');
    
    // 移动端优化：添加关闭动画
    if (isMobile && modalContent) {
        modalContent.style.transform = 'scale(0.9)';
        modalContent.style.opacity = '0';
        
        setTimeout(() => {
            modal.style.display = 'none';
            modalContent.style.transform = '';
            modalContent.style.opacity = '';
            // 恢复背景滚动
            document.body.style.overflow = '';
        }, 200);
    } else {
        modal.style.display = 'none';
        document.body.style.overflow = '';
    }
}

// 优化点击事件处理
window.onclick = function(event) {
    const modal = document.getElementById('response-modal');
    if (event.target === modal) {
        closeModal();
    }
}

// 移动端优化：添加触摸事件处理
if (isMobile) {
    window.addEventListener('touchstart', function(event) {
        const modal = document.getElementById('response-modal');
        if (event.target === modal) {
            closeModal();
        }
    }, { passive: true });
}

function showLoveNotification() {
    const options = {
        body: '我爱你 ❤️',
        icon: 'A.PNG',
        vibrate: [200, 100, 200]
    };
    new Notification('亲爱的', options);
}

function createCelebration() {
    const colors = ['#ff6b9d', '#4ecdc4', '#45b7d1', '#f9ca24', '#f0932b'];
    
    // 移动端优化：减少粒子数量以提升性能
    const particleCount = isMobile ? (isLowPerformance ? 20 : 30) : 50;
    const animationDuration = isMobile ? '2s' : '3s';
    const delayInterval = isMobile ? 30 : 50;
    
    for (let i = 0; i < particleCount; i++) {
        setTimeout(() => {
            const confetti = document.createElement('div');
            confetti.style.position = 'fixed';
            confetti.style.left = Math.random() * 100 + 'vw';
            confetti.style.top = '-10px';
            confetti.style.width = isMobile ? '8px' : '10px';
            confetti.style.height = isMobile ? '8px' : '10px';
            confetti.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
            confetti.style.borderRadius = '50%';
            confetti.style.pointerEvents = 'none';
            confetti.style.zIndex = '9999';
            confetti.style.animation = `confettiFall ${animationDuration} linear forwards`;
            
            // 移动端优化：使用 transform3d 启用硬件加速
            if (isMobile) {
                confetti.style.willChange = 'transform';
                confetti.style.transform = 'translate3d(0, 0, 0)';
            }
            
            document.body.appendChild(confetti);
            
            setTimeout(() => {
                if (confetti.parentNode) {
                    confetti.remove();
                }
            }, isMobile ? 2000 : 3000);
        }, i * delayInterval);
    }
}

const style = document.createElement('style');
style.textContent = `
    @keyframes confettiFall {
        0% {
            transform: translateY(-10px) rotate(0deg);
            opacity: 1;
        }
        100% {
            transform: translateY(100vh) rotate(360deg);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        closeModal();
    }
});

// 优化点击/触摸爱心效果
function createHeartEffect(x, y) {
    // 移动端性能优化：限制爱心效果频率
    if (isMobile && isLowPerformance) {
        // 低性能设备减少爱心效果
        if (Math.random() > 0.3) return;
    }
    
    const heart = document.createElement('div');
    heart.innerHTML = '💖';
    heart.style.position = 'fixed';
    heart.style.left = x + 'px';
    heart.style.top = y + 'px';
    heart.style.fontSize = isMobile ? '16px' : '20px';
    heart.style.pointerEvents = 'none';
    heart.style.zIndex = '9999';
    heart.style.animation = `heartFloat ${isMobile ? '0.8s' : '1s'} ease-out forwards`;
    
    // 移动端优化：启用硬件加速
    if (isMobile) {
        heart.style.willChange = 'transform';
        heart.style.transform = 'translate3d(0, 0, 0)';
    }
    
    document.body.appendChild(heart);
    
    setTimeout(() => {
        if (heart.parentNode) {
            heart.remove();
        }
    }, isMobile ? 800 : 1000);
}

// 桌面端点击事件
document.addEventListener('click', function(e) {
    // 避免在按钮和模态框上触发爱心效果
    if (e.target.closest('.btn') || e.target.closest('.modal') || e.target.closest('.close')) {
        return;
    }
    createHeartEffect(e.clientX, e.clientY);
});

// 移动端触摸事件
if (isMobile) {
    let touchTimeout;
    
    document.addEventListener('touchstart', function(e) {
        // 避免在交互元素上触发
        if (e.target.closest('.btn') || e.target.closest('.modal') || e.target.closest('.close')) {
            return;
        }
        
        // 防抖处理，避免过于频繁的触发
        clearTimeout(touchTimeout);
        touchTimeout = setTimeout(() => {
            const touch = e.touches[0];
            createHeartEffect(touch.clientX, touch.clientY);
        }, 100);
    }, { passive: true });
    
    // 清理超时
    document.addEventListener('touchend', function() {
        clearTimeout(touchTimeout);
    }, { passive: true });
}

const heartStyle = document.createElement('style');
heartStyle.textContent = `
    @keyframes heartFloat {
        0% {
            transform: translateY(0) scale(1);
            opacity: 1;
        }
        100% {
            transform: translateY(${isMobile ? '-30px' : '-50px'}) scale(${isMobile ? '1.2' : '1.5'});
            opacity: 0;
        }
    }
`;
document.head.appendChild(heartStyle);

// 移动端额外优化功能
if (isMobile) {
    // 屏幕方向变化处理
    window.addEventListener('orientationchange', function() {
        setTimeout(() => {
            // 重新计算模态框位置
            const modal = document.getElementById('response-modal');
            if (modal && modal.style.display === 'block') {
                const modalContent = modal.querySelector('.modal-content');
                if (modalContent) {
                    const viewportHeight = window.innerHeight;
                    const modalHeight = modalContent.offsetHeight;
                    const topPosition = Math.max(20, (viewportHeight - modalHeight) / 2);
                    modalContent.style.marginTop = topPosition + 'px';
                }
            }
        }, 500); // 等待方向变化完成
    });
    
    // 移动端滚动优化
    let ticking = false;
    
    function updateScrollElements() {
        // 这里可以添加滚动时的优化逻辑
        ticking = false;
    }
    
    window.addEventListener('scroll', function() {
        if (!ticking) {
            requestAnimationFrame(updateScrollElements);
            ticking = true;
        }
    }, { passive: true });
    
    // 移动端内存管理
    window.addEventListener('pagehide', function() {
        // 清理动画和定时器
        const hearts = document.querySelectorAll('[style*="heartFloat"]');
        hearts.forEach(heart => heart.remove());
        
        const confetti = document.querySelectorAll('[style*="confettiFall"]');
        confetti.forEach(particle => particle.remove());
    });
    
    // 移动端网络状态监控
    if ('connection' in navigator) {
        const connection = navigator.connection;
        
        function handleConnectionChange() {
            if (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g') {
                // 低速网络时进一步减少动画
                document.documentElement.style.setProperty('--animation-duration', '0.3s');
            } else {
                document.documentElement.style.setProperty('--animation-duration', '0.6s');
            }
        }
        
        connection.addEventListener('change', handleConnectionChange);
        handleConnectionChange(); // 初始检查
    }
    
    // 移动端触觉反馈（如果支持）
    function addHapticFeedback(element) {
        if ('vibrate' in navigator) {
            element.addEventListener('touchstart', function() {
                navigator.vibrate(10); // 轻微震动反馈
            }, { passive: true });
        }
    }
    
    // 为按钮添加触觉反馈
    document.addEventListener('DOMContentLoaded', function() {
        const buttons = document.querySelectorAll('.btn');
        buttons.forEach(addHapticFeedback);
    });
}

// 性能监控和自适应优化
if (isMobile && 'performance' in window) {
    let frameCount = 0;
    let lastTime = performance.now();
    
    function monitorPerformance() {
        frameCount++;
        const currentTime = performance.now();
        
        if (currentTime - lastTime >= 1000) {
            const fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
            
            // 如果帧率过低，自动降低动画质量
            if (fps < 30) {
                document.documentElement.classList.add('low-performance');
                // 可以在 CSS 中定义 .low-performance 类来减少动画效果
            } else if (fps > 50) {
                document.documentElement.classList.remove('low-performance');
            }
            
            frameCount = 0;
            lastTime = currentTime;
        }
        
        requestAnimationFrame(monitorPerformance);
    }
    
    // 延迟启动性能监控，避免影响初始加载
    setTimeout(() => {
        requestAnimationFrame(monitorPerformance);
    }, 3000);
}